package com.stop.think.shiro.service;

import com.stop.think.shiro.dao.EmpUsrDao;
import com.stop.think.shiro.dao.entity.EmpUsr;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Service
public class EmpUsrService {

    @Resource private EmpUsrDao empUsrDao;

    @PostConstruct
    public void initUsr() {
        EmpUsr adminUsr = new EmpUsr();
        adminUsr.setId(1L);
        adminUsr.setName("admin");
        adminUsr.setPassword("11111");
        adminUsr.setPerms("emp:usr:admin,emp:usr:admin_delete");
        adminUsr.setToken("adminToken");
        empUsrDao.save(adminUsr);
        EmpUsr normalUsr = new EmpUsr();
        normalUsr.setId(2L);
        normalUsr.setName("normalUsr");
        normalUsr.setPassword("123456");
        normalUsr.setPerms("emp:usr:normal");
        normalUsr.setToken("normalToken");
        empUsrDao.save(normalUsr);
    }

    public Set<String> findPermissionsByUsrId(Long usrId) {
        EmpUsr usr = empUsrDao.findById(usrId).orElseThrow(() -> new IncorrectCredentialsException("用户不存在"));
        return new HashSet<>(Arrays.asList(usr.getPerms().split(",")));
    }

    public Optional<EmpUsr> findByToken(String token) {
        return empUsrDao.findByToken(token);
    }
}
